<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
        <el-form-item label="提交哈希" prop="commitHash">
          <el-input
            v-model="queryParams.commitHash"
            placeholder="请输入提交哈希"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="仓库" prop="repositoryId">
          <el-select v-model="queryParams.repositoryId" placeholder="选择仓库" clearable style="width: 200px">
            <el-option 
              v-for="repo in repositories"
              :key="repo.id"
              :label="repo.name"
              :value="repo.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分支" prop="branchName">
          <el-select v-model="queryParams.branchName" placeholder="选择分支" clearable style="width: 200px">
            <el-option 
              v-for="branch in branches"
              :key="branch.branchName"
              :label="branch.branchName"
              :value="branch.branchName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="提交者" prop="author">
          <el-input
            v-model="queryParams.author"
            placeholder="请输入提交者"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="提交时间">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作工具栏 -->
    <el-card class="toolbar-card">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="Cherry"
            :disabled="single"
            @click="handleCherryPick"
          >Cherry-pick</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="RefreshLeft"
            :disabled="single"
            @click="handleRevert"
          >回滚</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="info"
            plain
            icon="Download"
            @click="handleExport"
          >导出</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 提交记录表格 -->
    <el-card>
      <el-table
        v-loading="loading"
        :data="commitList"
        @selection-change="handleSelectionChange"
        row-key="id"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="提交信息" align="left" min-width="300">
          <template #default="scope">
            <div class="commit-info">
              <div class="commit-message">
                <el-icon class="commit-icon"><Commit /></el-icon>
                <span class="message-text">{{ scope.row.message }}</span>
              </div>
              <div class="commit-meta">
                <span class="commit-hash">{{ scope.row.commitHash.substring(0, 8) }}</span>
                <span class="commit-author">{{ scope.row.author }}</span>
                <span class="commit-time">{{ formatTime(scope.row.commitTime) }}</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="仓库/分支" align="center" width="200">
          <template #default="scope">
            <div class="repo-branch">
              <div class="repo-name">{{ scope.row.repositoryName }}</div>
              <div class="branch-name">
                <el-icon><Branch /></el-icon>
                {{ scope.row.branchName }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="文件变更" align="center" width="120">
          <template #default="scope">
            <div class="file-changes">
              <el-tag type="success" size="small" v-if="scope.row.addedFiles > 0">
                +{{ scope.row.addedFiles }}
              </el-tag>
              <el-tag type="warning" size="small" v-if="scope.row.modifiedFiles > 0">
                ~{{ scope.row.modifiedFiles }}
              </el-tag>
              <el-tag type="danger" size="small" v-if="scope.row.deletedFiles > 0">
                -{{ scope.row.deletedFiles }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="代码变更" align="center" width="120">
          <template #default="scope">
            <div class="code-changes">
              <span class="additions">+{{ scope.row.additions || 0 }}</span>
              <span class="deletions">-{{ scope.row.deletions || 0 }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="标签" align="center" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.tag" type="info" size="small">
              {{ scope.row.tag }}
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="提交时间" align="center" prop="commitTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.commitTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button
              type="primary"
              icon="View"
              @click="handleView(scope.row)"
              link
            >查看</el-button>
            <el-button
              type="success"
              icon="Cherry"
              @click="handleCherryPick(scope.row)"
              link
            >Cherry-pick</el-button>
            <el-button
              type="warning"
              icon="RefreshLeft"
              @click="handleRevert(scope.row)"
              link
            >回滚</el-button>
          </template>
        </el-table-column>
      </el-table>

      <Pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- Cherry-pick对话框 -->
    <el-dialog
      v-model="cherryPickDialog.visible"
      title="Cherry-pick提交"
      width="500px"
    >
      <el-form :model="cherryPickDialog.form" label-width="100px">
        <el-form-item label="源提交">
          <el-input v-model="cherryPickDialog.sourceCommit" disabled />
        </el-form-item>
        <el-form-item label="目标分支">
          <el-select v-model="cherryPickDialog.form.targetBranch" placeholder="请选择目标分支" style="width: 100%">
            <el-option 
              v-for="branch in targetBranches"
              :key="branch.branchName"
              :label="branch.branchName"
              :value="branch.branchName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="提交信息">
          <el-input
            v-model="cherryPickDialog.form.commitMessage"
            type="textarea"
            :rows="3"
            placeholder="请输入提交信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cherryPickDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="confirmCherryPick" :loading="cherryPickDialog.loading">确定</el-button>
      </template>
    </el-dialog>

    <!-- 回滚对话框 -->
    <el-dialog
      v-model="revertDialog.visible"
      title="回滚提交"
      width="500px"
    >
      <el-form :model="revertDialog.form" label-width="100px">
        <el-form-item label="回滚提交">
          <el-input v-model="revertDialog.sourceCommit" disabled />
        </el-form-item>
        <el-form-item label="回滚类型">
          <el-radio-group v-model="revertDialog.form.revertType">
            <el-radio label="SOFT">软回滚（保留工作区）</el-radio>
            <el-radio label="HARD">硬回滚（清除所有更改）</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="回滚说明">
          <el-input
            v-model="revertDialog.form.revertMessage"
            type="textarea"
            :rows="3"
            placeholder="请输入回滚说明"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="revertDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="confirmRevert" :loading="revertDialog.loading">确定回滚</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getCommitPage, 
  getCommitDetail,
  cherryPickCommit,
  revertCommit,
  exportCommits,
  getRepositoryList,
  getBranchList
} from '@/api/version'
import { useRouter } from 'vue-router'
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination/index.vue'

const router = useRouter()

// 响应式数据
const loading = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const commitList = ref([])
const repositories = ref([])
const branches = ref([])
const targetBranches = ref([])
const queryFormRef = ref()
const dateRange = ref([])

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  commitHash: undefined,
  repositoryId: undefined,
  branchName: undefined,
  author: undefined,
  startTime: undefined,
  endTime: undefined
})

// Cherry-pick对话框
const cherryPickDialog = reactive({
  visible: false,
  loading: false,
  sourceCommit: '',
  commitId: null,
  form: {
    targetBranch: '',
    commitMessage: ''
  }
})

// 回滚对话框
const revertDialog = reactive({
  visible: false,
  loading: false,
  sourceCommit: '',
  commitId: null,
  form: {
    revertType: 'SOFT',
    revertMessage: ''
  }
})

// 获取提交记录列表
const getList = async () => {
  loading.value = true
  try {
    if (dateRange.value && dateRange.value.length === 2) {
      queryParams.startTime = dateRange.value[0]
      queryParams.endTime = dateRange.value[1]
    } else {
      queryParams.startTime = undefined
      queryParams.endTime = undefined
    }
    
    const response = await getCommitPage(queryParams)
    if (response.code === 200) {
      commitList.value = response.data.records || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取提交记录失败')
    }
  } catch (error) {
    console.error('获取提交记录失败:', error)
    ElMessage.error('获取提交记录失败')
  } finally {
    loading.value = false
  }
}

// 获取仓库列表
const getRepositories = async () => {
  try {
    const response = await getRepositoryList()
    if (response.code === 200) {
      repositories.value = response.data || []
    }
  } catch (error) {
    console.error('获取仓库列表失败:', error)
  }
}

// 获取分支列表
const getBranches = async (repositoryId) => {
  try {
    const response = await getBranchList({ repositoryId })
    if (response.code === 200) {
      branches.value = response.data || []
      targetBranches.value = response.data || []
    }
  } catch (error) {
    console.error('获取分支列表失败:', error)
  }
}

// 监听仓库变化
watch(() => queryParams.repositoryId, (newVal) => {
  if (newVal) {
    getBranches(newVal)
  } else {
    branches.value = []
  }
  queryParams.branchName = undefined
})

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  dateRange.value = []
  queryFormRef.value?.resetFields()
  branches.value = []
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 查看按钮操作
const handleView = (row) => {
  router.push(`/version/commit/detail/${row.id}`)
}

// Cherry-pick按钮操作
const handleCherryPick = (row) => {
  const commit = row.id ? row : commitList.value.find(item => ids.value.includes(item.id))
  if (!commit) {
    ElMessage.warning('请选择要Cherry-pick的提交')
    return
  }
  
  cherryPickDialog.commitId = commit.id
  cherryPickDialog.sourceCommit = `${commit.commitHash.substring(0, 8)} - ${commit.message}`
  cherryPickDialog.form = {
    targetBranch: '',
    commitMessage: commit.message
  }
  cherryPickDialog.visible = true
  getBranches(commit.repositoryId)
}

// 确认Cherry-pick
const confirmCherryPick = async () => {
  if (!cherryPickDialog.form.targetBranch) {
    ElMessage.warning('请选择目标分支')
    return
  }
  
  try {
    cherryPickDialog.loading = true
    await cherryPickCommit(cherryPickDialog.commitId, cherryPickDialog.form)
    ElMessage.success('Cherry-pick成功')
    cherryPickDialog.visible = false
    getList()
  } catch (error) {
    console.error('Cherry-pick失败:', error)
    ElMessage.error('Cherry-pick失败')
  } finally {
    cherryPickDialog.loading = false
  }
}

// 回滚按钮操作
const handleRevert = (row) => {
  const commit = row.id ? row : commitList.value.find(item => ids.value.includes(item.id))
  if (!commit) {
    ElMessage.warning('请选择要回滚的提交')
    return
  }
  
  revertDialog.commitId = commit.id
  revertDialog.sourceCommit = `${commit.commitHash.substring(0, 8)} - ${commit.message}`
  revertDialog.form = {
    revertType: 'SOFT',
    revertMessage: `Revert "${commit.message}"`
  }
  revertDialog.visible = true
}

// 确认回滚
const confirmRevert = async () => {
  try {
    await ElMessageBox.confirm('确认要回滚此提交吗？此操作不可逆！', '确认回滚', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    revertDialog.loading = true
    await revertCommit(revertDialog.commitId, revertDialog.form)
    ElMessage.success('回滚成功')
    revertDialog.visible = false
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('回滚失败:', error)
      ElMessage.error('回滚失败')
    }
  } finally {
    revertDialog.loading = false
  }
}

// 导出按钮操作
const handleExport = async () => {
  try {
    await exportCommits(queryParams)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 工具函数
const parseTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString()
}

const formatTime = (time) => {
  if (!time) return ''
  const now = new Date()
  const date = new Date(time)
  const diff = now - date
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  
  if (days === 0) {
    const hours = Math.floor(diff / (1000 * 60 * 60))
    if (hours === 0) {
      const minutes = Math.floor(diff / (1000 * 60))
      return `${minutes}分钟前`
    }
    return `${hours}小时前`
  } else if (days < 7) {
    return `${days}天前`
  } else {
    return date.toLocaleDateString()
  }
}

// 页面加载时获取数据
onMounted(() => {
  getList()
  getRepositories()
})
</script>

<style lang="scss" scoped>
.search-card {
  margin-bottom: 16px;
}

.toolbar-card {
  margin-bottom: 16px;
}

.mb8 {
  margin-bottom: 8px;
}

.commit-info {
  text-align: left;
  
  .commit-message {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 8px;
    
    .commit-icon {
      color: #409eff;
      flex-shrink: 0;
    }
    
    .message-text {
      font-weight: 500;
      color: #303133;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }
  
  .commit-meta {
    display: flex;
    gap: 12px;
    font-size: 12px;
    color: #909399;
    
    .commit-hash {
      font-family: monospace;
      background-color: #f5f5f5;
      padding: 2px 6px;
      border-radius: 3px;
      color: #606266;
    }
  }
}

.repo-branch {
  .repo-name {
    font-weight: 500;
    color: #303133;
    margin-bottom: 4px;
  }
  
  .branch-name {
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 12px;
    color: #606266;
  }
}

.file-changes {
  display: flex;
  flex-direction: column;
  gap: 2px;
  align-items: center;
}

.code-changes {
  display: flex;
  flex-direction: column;
  gap: 2px;
  font-size: 12px;
  
  .additions {
    color: #67c23a;
  }
  
  .deletions {
    color: #f56c6c;
  }
}
</style>
